<template>
  <nut-navbar :title="store.lessonDetail.title" left-show @click-back="router.back" />
  <div class="video">
    <nut-video
      ref="videoRef"
      :source="store.video"
      :options="options"
      @play="handlePlay"
      @pause="handlePause"
      @playend="handlePlayend"
    />
  </div>
  <nut-divider />
  <nut-tabs v-model="currentTab">
    <nut-tab-pane title="课程章节" pane-key="1">
      <nut-cell
        v-if="store.chapterList && store.chapterList.length > 0"
        v-for="(chapter, index) in store.chapterList"
        :key="index"
        :title="chapter.title"
        :sub-title="chapter.play ? '正在播放' : ''"
        :desc="chapter.progress + '%'"
        @click="handlePlayChapter(chapter.id)"
      />
      <div class="notext" v-else>无课程章节</div>
    </nut-tab-pane>
    <nut-tab-pane title="课件资料" pane-key="2">
      <nut-cell
        v-if="store.ebookList && store.ebookList.length > 0"
        v-for="(ebook, index) in store.ebookList"
        :key="index"
        :title="ebook.title"
        :desc="ebook.size"
        @click="handleDownFile(ebook.file)"
      />
      <div class="notext" v-else>无课件资料</div>
    </nut-tab-pane>
  </nut-tabs>
</template>

<script setup lang="ts">
//websocket for study
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStudentLessonStore } from '@/stores/studentLessons'
import cfg from '@/config/config'
import socket from '@/util/websocket'

const store = useStudentLessonStore()
const route = useRoute()
const router = useRouter()
const currentTab = ref<number>(1)
const videoRef = ref()
const options = ref({
  autoplay: true,
  controls: true
})

onMounted(async () => {
  if (route.params.id && route.params.id > 0) {
    socket.connect(cfg.websocketUrl)
    await store.loadDetail(parseInt(route.params.id as string))
    await store.getChapters(store.lessonDetail.id)
    await store.getEbooks(store.lessonDetail.id)
    handlePlayChapter(route.query.chapterId | 0)
  } else {
    router.back()
  }
})
onBeforeUnmount(() => {
  if (videoRef) {
    videoRef.value.stop()
  }
  socket.close()
})

const handlePlay = () => {
  if (socket.connected) {
    socket.sendPlay(store.lessonDetail.id, store.video.id)
    socket.setHeart(store.lessonDetail.id, store.video.id, 5000)
  }
}

const handlePause = () => {
  if (socket.connected) {
    socket.sendStop(store.lessonDetail.id, store.video.id)
    socket.clearHeart()
  }
}

const handlePlayend = () => {
  if (socket.connected) {
    socket.sendStop(store.lessonDetail.id, store.video.id)
    socket.clearHeart()
  }
}

const handlePlayChapter = (chapterId: number) => {
  if (videoRef.value) {
    videoRef.value.stop()
  }
  store.playVideo(chapterId)
  if (videoRef.value) {
    videoRef.value.play()
  }
}

const handleDownFile = (file: string) => {
  window.open(cfg.fileUrl(file))
}
</script>
